<script lang="ts" setup>
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import { message } from 'ant-design-vue';

interface Props {
  visible: boolean;
  application: any;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const activeTab = ref('performance');
const logLevel = ref('all');
const alertModalVisible = ref(false);
const alertFormRef = ref();

// 监控数据
const monitorData = reactive({
  cpu: 45.2,
  memory: 68.7,
  disk: 23.1,
  network: 12.5,
});

// 应用日志
const logs = ref([
  {
    id: 1,
    timestamp: '2024-01-15 10:30:15',
    level: 'info',
    message: '应用启动成功',
  },
  {
    id: 2,
    timestamp: '2024-01-15 10:30:20',
    level: 'info',
    message: '数据库连接建立',
  },
  {
    id: 3,
    timestamp: '2024-01-15 10:30:25',
    level: 'warn',
    message: '内存使用率较高: 75%',
  },
  {
    id: 4,
    timestamp: '2024-01-15 10:30:30',
    level: 'error',
    message: 'Redis连接失败',
  },
]);

// 告警规则
const alerts = ref([
  {
    id: 1,
    name: 'CPU告警',
    metric: 'cpu',
    threshold: 80,
    duration: 5,
    enabled: true,
    notifications: ['email', 'webhook'],
  },
  {
    id: 2,
    name: '内存告警',
    metric: 'memory',
    threshold: 85,
    duration: 3,
    enabled: true,
    notifications: ['email'],
  },
  {
    id: 3,
    name: '磁盘告警',
    metric: 'disk',
    threshold: 90,
    duration: 10,
    enabled: false,
    notifications: ['email', 'sms'],
  },
]);

// 健康检查服务
const healthServices = ref([
  { name: 'Web服务', status: 'healthy', description: 'HTTP服务正常运行' },
  { name: '数据库', status: 'healthy', description: 'MySQL连接正常' },
  { name: '缓存服务', status: 'unhealthy', description: 'Redis连接异常' },
  { name: '文件存储', status: 'healthy', description: '文件系统正常' },
]);

// 响应时间
const responseTimes = ref([
  { path: '/api/users', time: 120 },
  { path: '/api/orders', time: 85 },
  { path: '/api/products', time: 95 },
  { path: '/api/analytics', time: 250 },
]);

// 告警表单
const alertForm = reactive({
  id: null,
  name: '',
  metric: '',
  threshold: 80,
  duration: 5,
  notifications: [],
  description: '',
});

// 表格列定义
const alertColumns = [
  { title: '告警名称', dataIndex: 'name', key: 'name' },
  { title: '监控指标', dataIndex: 'metric', key: 'metric' },
  { title: '阈值', dataIndex: 'threshold', key: 'threshold' },
  { title: '持续时间', dataIndex: 'duration', key: 'duration' },
  { title: '状态', key: 'status' },
  { title: '操作', key: 'action', width: 120 },
];

// 表单验证规则
const alertRules = {
  name: [{ required: true, message: '请输入告警名称' }],
  metric: [{ required: true, message: '请选择监控指标' }],
  threshold: [{ required: true, message: '请输入阈值' }],
  duration: [{ required: true, message: '请输入持续时间' }],
};

// 计算属性
const filteredLogs = computed(() => {
  if (logLevel.value === 'all') {
    return logs.value;
  }
  return logs.value.filter((log) => log.level === logLevel.value);
});

// 工具函数
const getCpuColor = (value: number) => {
  if (value < 50) return '#52c41a';
  if (value < 80) return '#faad14';
  return '#ff4d4f';
};

const getMemoryColor = (value: number) => {
  if (value < 60) return '#52c41a';
  if (value < 85) return '#faad14';
  return '#ff4d4f';
};

const getDiskColor = (value: number) => {
  if (value < 70) return '#52c41a';
  if (value < 90) return '#faad14';
  return '#ff4d4f';
};

const getResponseTimeClass = (time: number) => {
  if (time < 100) return 'fast';
  if (time < 200) return 'normal';
  return 'slow';
};

// 方法
const refreshLogs = () => {
  // 模拟刷新日志
  message.success('日志已刷新');
};

const clearLogs = () => {
  logs.value = [];
  message.success('日志已清空');
};

const addAlert = () => {
  alertForm.id = null;
  alertForm.name = '';
  alertForm.metric = '';
  alertForm.threshold = 80;
  alertForm.duration = 5;
  alertForm.notifications = [];
  alertForm.description = '';
  alertModalVisible.value = true;
};

const editAlert = (alert: any) => {
  Object.assign(alertForm, alert);
  alertModalVisible.value = true;
};

const deleteAlert = (id: number) => {
  alerts.value = alerts.value.filter((alert) => alert.id !== id);
  message.success('告警规则已删除');
};

const updateAlertStatus = (alert: any) => {
  message.success(`${alert.name} ${alert.enabled ? '已启用' : '已禁用'}`);
};

const saveAlert = async () => {
  try {
    await alertFormRef.value?.validate();

    if (alertForm.id) {
      // 更新告警
      const index = alerts.value.findIndex((a) => a.id === alertForm.id);
      if (index !== -1) {
        alerts.value[index] = { ...alertForm };
      }
    } else {
      // 新增告警
      const newId = Math.max(...alerts.value.map((a) => a.id), 0) + 1;
      alerts.value.push({
        ...alertForm,
        id: newId,
        enabled: true,
      });
    }

    message.success('告警规则保存成功');
    alertModalVisible.value = false;
  } catch (error) {
    console.error('保存告警规则失败:', error);
  }
};

const cancelAlert = () => {
  alertModalVisible.value = false;
};

// 模拟实时数据更新
let monitorInterval: NodeJS.Timeout;
letmonitorIntervalletmonitorInterval;

onMounted(() => {
  monitorInterval = setInterval(() => {
    // 模拟数据变化
    monitorData.cpu = Math.random() * 100;
    monitorData.memory = Math.random() * 100;
    monitorData.disk = Math.random() * 100;
    monitorData.network = Math.random() * 50;
  }, 5000);
});

onUnmounted(() => {
  if (monitorInterval) {
    clearInterval(monitorInterval);
  }
});

const handleCancel = () => {
  emit('update:visible', false);
};
</script>

<template>
  <div class="application-monitor">
    <a-modal
      :open="visible"
      title="应用监控"
      width="1200px"
      :footer="null"
      @cancel="handleCancel"
      @update:open="(val) => emit('update:visible', val)"
    >
      <div class="monitor-container">
        <!-- 监控概览 -->
        <a-row :gutter="16" class="monitor-overview">
          <a-col :span="6">
            <a-card size="small">
              <a-statistic
                title="CPU使用率"
                :value="monitorData.cpu"
                :precision="1"
                suffix="%"
                :value-style="{ color: getCpuColor(monitorData.cpu) }"
              />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card size="small">
              <a-statistic
                title="内存使用率"
                :value="monitorData.memory"
                :precision="1"
                suffix="%"
                :value-style="{ color: getMemoryColor(monitorData.memory) }"
              />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card size="small">
              <a-statistic
                title="磁盘使用率"
                :value="monitorData.disk"
                :precision="1"
                suffix="%"
                :value-style="{ color: getDiskColor(monitorData.disk) }"
              />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card size="small">
              <a-statistic
                title="网络流量"
                :value="monitorData.network"
                :precision="1"
                suffix="MB/s"
                :value-style="{ color: '#1890ff' }"
              />
            </a-card>
          </a-col>
        </a-row>

        <!-- 监控选项卡 -->
        <a-tabs
          :active-key="activeTab"
          type="card"
          class="monitor-tabs"
          @update:active-key="activeTab = $event"
        >
          <!-- 性能监控 -->
          <a-tab-pane key="performance" tab="性能监控">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-card title="CPU使用率趋势" size="small">
                  <div class="chart-container">
                    <div class="chart-placeholder">
                      <a-progress
                        type="circle"
                        :percent="monitorData.cpu"
                        :stroke-color="getCpuColor(monitorData.cpu)"
                      />
                      <p>实时CPU使用率</p>
                    </div>
                  </div>
                </a-card>
              </a-col>
              <a-col :span="12">
                <a-card title="内存使用率趋势" size="small">
                  <div class="chart-container">
                    <div class="chart-placeholder">
                      <a-progress
                        type="circle"
                        :percent="monitorData.memory"
                        :stroke-color="getMemoryColor(monitorData.memory)"
                      />
                      <p>实时内存使用率</p>
                    </div>
                  </div>
                </a-card>
              </a-col>
            </a-row>
          </a-tab-pane>

          <!-- 应用日志 -->
          <a-tab-pane key="logs" tab="应用日志">
            <div class="logs-container">
              <div class="logs-header">
                <a-space>
                  <a-select
                    v-model:value="logLevel"
                    style="width: 120px"
                    placeholder="日志级别"
                  >
                    <a-select-option value="all">全部</a-select-option>
                    <a-select-option value="error">错误</a-select-option>
                    <a-select-option value="warn">警告</a-select-option>
                    <a-select-option value="info">信息</a-select-option>
                    <a-select-option value="debug">调试</a-select-option>
                  </a-select>
                  <a-button @click="refreshLogs">
                    <template #icon>
                      <IconifyIcon icon="ant-design:reload-outlined" />
                    </template>
                    刷新
                  </a-button>
                  <a-button @click="clearLogs">清空</a-button>
                </a-space>
              </div>

              <div class="logs-content">
                <div
                  v-for="log in filteredLogs"
                  :key="log.id"
                  class="log-item"
                  :class="log.level"
                >
                  <span class="log-time">{{ log.timestamp }}</span>
                  <span class="log-level">[{{ log.level.toUpperCase() }}]</span>
                  <span class="log-message">{{ log.message }}</span>
                </div>
              </div>
            </div>
          </a-tab-pane>

          <!-- 告警设置 -->
          <a-tab-pane key="alerts" tab="告警设置">
            <a-card title="告警规则" size="small" style="margin-bottom: 16px">
              <a-table
                :columns="alertColumns"
                :data-source="alerts"
                :pagination="false"
                size="small"
                row-key="id"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'status'">
                    <a-switch
                      v-model:checked="record.enabled"
                      size="small"
                      @change="updateAlertStatus(record)"
                    />
                  </template>
                  <template v-else-if="column.key === 'action'">
                    <a-space>
                      <a-button
                        type="link"
                        size="small"
                        @click="editAlert(record)"
                      >
                        编辑
                      </a-button>
                      <a-button
                        type="link"
                        size="small"
                        danger
                        @click="deleteAlert(record.id)"
                      >
                        删除
                      </a-button>
                    </a-space>
                  </template>
                </template>
              </a-table>

              <div class="alert-actions">
                <a-button type="primary" @click="addAlert">
                  <template #icon>
                    <IconifyIcon icon="ant-design:plus-outlined" />
                  </template>
                  添加告警规则
                </a-button>
              </div>
            </a-card>
          </a-tab-pane>

          <!-- 健康检查 -->
          <a-tab-pane key="health" tab="健康检查">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-card title="服务状态" size="small">
                  <a-list size="small">
                    <a-list-item
                      v-for="service in healthServices"
                      :key="service.name"
                    >
                      <template #actions>
                        <a-tag
                          :color="
                            service.status === 'healthy' ? 'green' : 'red'
                          "
                        >
                          {{ service.status === 'healthy' ? '正常' : '异常' }}
                        </a-tag>
                      </template>
                      <a-list-item-meta>
                        <template #title>{{ service.name }}</template>
                        <template #description>
                          {{ service.description }}
                        </template>
                      </a-list-item-meta>
                    </a-list-item>
                  </a-list>
                </a-card>
              </a-col>
              <a-col :span="12">
                <a-card title="响应时间" size="small">
                  <div class="response-times">
                    <div
                      v-for="endpoint in responseTimes"
                      :key="endpoint.path"
                      class="endpoint-item"
                    >
                      <span class="endpoint-path">{{ endpoint.path }}</span>
                      <span
                        class="endpoint-time"
                        :class="getResponseTimeClass(endpoint.time)"
                      >
                        {{ endpoint.time }}ms
                      </span>
                    </div>
                  </div>
                </a-card>
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-modal>

    <!-- 告警编辑模态框 -->
    <a-modal
      v-model:open="alertModalVisible"
      title="告警规则"
      width="600px"
      @ok="saveAlert"
      @cancel="cancelAlert"
    >
      <a-form
        ref="alertFormRef"
        :model="alertForm"
        :rules="alertRules"
        layout="vertical"
      >
        <a-form-item label="告警名称" name="name">
          <a-input
            v-model:value="alertForm.name"
            placeholder="请输入告警名称"
          />
        </a-form-item>

        <a-form-item label="监控指标" name="metric">
          <a-select
            v-model:value="alertForm.metric"
            placeholder="请选择监控指标"
          >
            <a-select-option value="cpu">CPU使用率</a-select-option>
            <a-select-option value="memory">内存使用率</a-select-option>
            <a-select-option value="disk">磁盘使用率</a-select-option>
            <a-select-option value="network">网络流量</a-select-option>
            <a-select-option value="response_time">响应时间</a-select-option>
          </a-select>
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="阈值" name="threshold">
              <a-input-number
                v-model:value="alertForm.threshold"
                :min="0"
                :max="100"
                style="width: 100%"
                placeholder="请输入阈值"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="持续时间(分钟)" name="duration">
              <a-input-number
                v-model:value="alertForm.duration"
                :min="1"
                :max="60"
                style="width: 100%"
                placeholder="持续时间"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="通知方式" name="notifications">
          <a-checkbox-group v-model:value="alertForm.notifications">
            <a-checkbox value="email">邮件通知</a-checkbox>
            <a-checkbox value="sms">短信通知</a-checkbox>
            <a-checkbox value="webhook">Webhook</a-checkbox>
          </a-checkbox-group>
        </a-form-item>

        <a-form-item label="告警描述" name="description">
          <a-textarea
            v-model:value="alertForm.description"
            :rows="3"
            placeholder="请输入告警描述"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
.application-monitor {
  .monitor-container {
    .monitor-overview {
      margin-bottom: 24px;
    }

    .monitor-tabs {
      .chart-container {
        height: 200px;
        display: flex;
        align-items: center;
        justify-content: center;

        .chart-placeholder {
          text-align: center;

          p {
            margin-top: 16px;
            color: #666;
          }
        }
      }
    }

    .logs-container {
      .logs-header {
        margin-bottom: 16px;
      }

      .logs-content {
        height: 300px;
        overflow-y: auto;
        background: #fafafa;
        border: 1px solid #e8e8e8;
        border-radius: 4px;
        padding: 8px;

        .log-item {
          display: flex;
          margin-bottom: 4px;
          font-family: 'Courier New', monospace;
          font-size: 12px;

          .log-time {
            color: #666;
            margin-right: 8px;
            min-width: 150px;
          }

          .log-level {
            margin-right: 8px;
            min-width: 60px;
            font-weight: bold;
          }

          .log-message {
            flex: 1;
          }

          &.info {
            color: #1890ff;
          }

          &.warn {
            color: #faad14;
          }

          &.error {
            color: #ff4d4f;
          }
        }
      }
    }

    .alert-actions {
      margin-top: 16px;
      text-align: center;
    }

    .response-times {
      .endpoint-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .endpoint-path {
          font-family: monospace;
          color: #333;
        }

        .endpoint-time {
          font-weight: bold;

          &.fast {
            color: #52c41a;
          }

          &.normal {
            color: #faad14;
          }

          &.slow {
            color: #ff4d4f;
          }
        }
      }
    }
  }
}
</style>
